package com.example.multactivity

import android.os.Bundle
import android.widget.TextView
import android.widget.Button
import androidx.activity.ComponentActivity
import android.os.Looper
import android.os.Handler
import java.util.Locale
import android.util.Log

class FifthActivity : ComponentActivity() {

    var seconds = 0
    var running = false
    var wasRunning = false

    private lateinit var textViewTimer : TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fifth)

        val buttonStrat = findViewById<Button>(R.id.button_start)
        val buttonStop = findViewById<Button>(R.id.button_stop)
        val buttonRestart = findViewById<Button>(R.id.button_restart)
        textViewTimer = findViewById(R.id.textView_timer)

        if(savedInstanceState != null){
            seconds = savedInstanceState.getInt("second")
            running = savedInstanceState.getBoolean("running")
            wasRunning = savedInstanceState.getBoolean(" wasRunning")
        }

        runTimer()

        buttonStrat.setOnClickListener{
            running = true
        }

        buttonStop.setOnClickListener{
            running = false
        }

        buttonRestart.setOnClickListener{
            running = true
            seconds = 0
        }

    }

    fun runTimer() {
        val handler = Handler(Looper.getMainLooper())

        val runnable = object : Runnable {
            override fun run() {
                val hours = seconds / 3600
                val minutes = (seconds % 3600) / 60
                val secs = seconds % 60
                // 格式化为 HH:MM:SS
                textViewTimer.text = String.format(Locale.US,"%02d:%02d:%02d", hours, minutes, secs)
                if (running) {
                    seconds++
                }
                handler.postDelayed(this, 1000)// 每隔 1000ms (1秒) 再次调用自己
            }
        }
        handler.post(runnable)// 启动定时器：第一次调用 runnable
    }

    override fun onSaveInstanceState(outState: Bundle){
        super.onSaveInstanceState(outState)
        Log.d( "Life cycle","onSaveInstanceState")
        outState.putInt("seconds",seconds)
        outState.putBoolean("running",running)
        outState.putBoolean("wasRunning",wasRunning)
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d("Life cycle", "onDestroy")
    }

    override fun onStart() {
        super.onStart()
        Log.d("Life cycle", "onStart")
    }

    override fun onStop() {
        super.onStop()
        Log.d("Life cycle", "onStop")
    }

    override fun onResume() {
        super.onResume()
        Log.d("Life cycle", "onResume")
        if(wasRunning){
            running = true
        }
    }

    override fun onPause() {
        super.onPause()
        Log.d("Life cycle", "onPause")
        wasRunning = running
        running = false
    }

}